<template>
  <div class="warpper-box">
    <div class="inner_box">
      <el-form :inline="true" size="small" :model="formInline" ref="formInline">
        <el-form-item label="移入时间" prop="time">
           <el-date-picker
            v-model="formInline.time"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item
        label="入库类别"
        prop="applyCategoryId"
      >
        <el-cascader
          placeholder="支持搜索，多选"
          filterable
          v-model="formInline.applyCategoryId"
          collapse-tags
          :options="treeData"
          :props="{multiple: true,emitPath: false}"
          clearable
        ></el-cascader>
      </el-form-item>
         <el-form-item label="公司名称" prop="name">
          <el-input v-model="formInline.name" placeholder="公司名称"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="contactPerson">
          <el-input
            v-model="formInline.contactPerson"
            placeholder="姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="contactPhone">
          <el-input
            v-model="formInline.contactPhone"
            placeholder="电话"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formInline.email" placeholder="邮箱"></el-input>
        </el-form-item>
        <el-form-item label="移入方式" prop="pauseType">
            <el-select v-model="formInline.pauseType" placeholder="请选择">
                <el-option
                v-for="item in moveData"
                :key="item.value"
                :label="item.label"
                :value="item.value">
                </el-option>
            </el-select>
        </el-form-item>
         <el-form-item label="移入事由" prop="pauseReason">
          <el-input v-model="formInline.pauseReason" placeholder="模糊查询"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="loadList(true)">搜索</el-button>
            <el-button type="primary" icon="el-icon-setting" @click="reset('formInline')">重置</el-button>
            <el-button type="primary" size="small" :disabled="tables.tableData.length == 0" @click="dataXlsx()">导出EXCEL</el-button>
        </el-form-item>
      </el-form>
      <supplier-common-list
       ref="createSupplier"
       :tableData="tables.tableData" 
       :tableLabel="tables.tableLabel"
       :models="tables" 
       :key="tableKey"
       :operateWin="180"
       @on-search-click="loadList"
       @on-detail-click="supplierDetailClick"
       @on-store-detail-click="onStoreDetailClick"
       @on-restore-click="restoreClick"
       @on-remark-click="remarkClick"
       />
    </div>

      <supplierDetail ref="createSupplierDetail" />
       <infoStore ref="createInfoStore" />

  </div>
</template>

<script>
import moment from "moment";
import { mapGetters, mapActions } from "vuex";
import { getSupplierStorePage, getSupplierCategoryTree,supplierRestorePause,updateStoreRemark } from "@/api/supplier_api";
import { checkEmail, checkPhone, TreeArrar } from "@/utils/index";
import { SUPPLIER_PAUSE_LABEL,moveOptions } from "@/views/supplier/supplierModel/config";
import supplierDetail from '@/views/supplier/supplierModel/supplier_detail.vue'
import supplierCommonList from "@/views/supplier/supplierModel/supplier_common_list.vue"
 import infoStore from '@/views/supplier/supplierModel/info_store.vue'
export default {
  components: {
    supplierDetail,
        supplierCommonList,
    infoStore
  },
  data() {
    return {
      formInline: {
        name: "",
        applyCategoryId:[],
        contactPerson: "",
        contactPhone: "",
        email: "",
        pauseReason:"",
        pauseType:"",
        time:[]
      },
      treeData:[],
      tableKey: 0,
      tables:{
        total: 0,
        isStore:true,
        tableData: [],
        tableLabel:SUPPLIER_PAUSE_LABEL
      },
      models: {
        pageNum: 1,
        pageSize: 10
        },
        moveData:moveOptions
    };
  },
  computed: {
    ...mapGetters(["findType"])
  },
  mounted() {
    this.loadList(true);
    this.categoryList()
  },
  methods: {
    async categoryList() {
        const { code, data } = await getSupplierCategoryTree();
      if (code == 200) {
       if (data && data.length) {
          let NewData = data.map((ele) => TreeArrar(ele))
         this.treeData = NewData
       } 
     }
    },
    async loadList(formData) {
      let param = {};
      if (typeof formData === 'boolean') {
        this.models.pageNum = 1;
        this.models.pageSize = 10;
        if (this.$refs.createSupplier) {
          this.$refs.createSupplier.clearSelected()
        }
      }
      if (typeof formData === 'object') {
         this.models.pageNum = formData.pageNum;
        this.models.pageSize = formData.pageSize;
        if (this.$refs.createSupplier) {
          this.$refs.createSupplier.clearSelected()
        }
      }
      if (
        this.formInline.contactPhone &&
        !checkPhone(this.formInline.contactPhone)
      ) {
        this.$message.error("联系电话输入格式有误");
        return;
      }
      if (this.formInline.email && !checkEmail(this.formInline.email)) {
        this.$message.error("邮箱输入格式有误");
        return;
      }
      if (this.formInline.applyCategoryId&&this.formInline.applyCategoryId.length) {
        param.applyCategoryIds = this.formInline.applyCategoryId
      }

      if (this.formInline.time && this.formInline.time.length) {
        param.pauseStartTime = this.formInline.time[0]
        param.pauseEndTime = this.formInline.time[1]
      }
      param.pauseReason = this.formInline.pauseReason;
      param.contactPhone = this.formInline.contactPhone;
      param.email = this.formInline.email;
      param.contactPerson = this.formInline.contactPerson;
      param.name = this.formInline.name;
      param.pauseType = this.formInline.pauseType;
      param.pageNum = this.models.pageNum
      param.pageSize = this.models.pageSize;
     // param.queryType = this.findType["pass"];
     // param.tag = "2"
      param.isPaused =1
      const { code, data } = await getSupplierStorePage(param);
      if (code == 200) {
        data.list.forEach((v,i) => {
          v.restoreApply = true
          v.setRemark = true
          v.storeSupplierId = v.id
            v.id = v.applyId
        })
        this.tables.tableData = data.list
        this.tables.total = data.total
      }
    },
    reset(formName){
      this.$refs[formName].resetFields();
      this.loadList(true);
    },
    supplierDetailClick(row) {
      this.$refs.createSupplierDetail.openDetail(row,1)
    },
    onStoreDetailClick(row) {
      this.$refs.createInfoStore.openDetail(row)
    },
    restoreClick(row) {
      let txt = `确定恢复库名为【${row.applyCategoryName}】`
        this.$confirm(txt, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        let param = {}
        param.id = row.storeSupplierId
        param.storeApplicationId = row.id
        const {code} = await supplierRestorePause(param);
        if(code === 200){
          this.$message.success("操作成功");
          this.loadList(true);
        }
      }).catch(() => {});
    },
    remarkClick(row) {
      let that = this
       this.$prompt('请输入备注', '备注信息', {
        confirmButtonText: '保存',
           cancelButtonText: '取消',
         inputPlaceholder: '请输入备注信息',
         inputValue: row.otherRemarks,
         closeOnClickModal:false,
          beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            const value = instance.inputValue;
            const isValid = this.validateInput(value);
            if (isValid) {
              try {
                row.id = row.storeSupplierId
                row.remarks = value
                const _isValid = await this.mockApiCall(row);
                if (_isValid) {
                  that.loadList();
                  done();
                } 
              } catch (error) {
                this.$message.error('接口请求出错，请稍后重试');
              }
            } else {
              this.$message.error('请输入备注信息');
            }
          } else {
            done();
          }
        },
      }).then(() => {}).catch(() => {});
    },
    mockApiCall(result){
      return new Promise(async (resolve) => {
          const data = await updateStoreRemark(result)
          resolve(data);
      });
    },
    validateInput(value){
      return value.trim()!== '';
    },
     async dataXlsx() {
      let param = {};
      param.pageNum = 1;
      param.pageSize = this.tables.total;
       if (
        this.formInline.contactPhone &&
        !checkPhone(this.formInline.contactPhone)
      ) {
        this.$message.error("联系电话输入格式有误");
        return;
      }
      if (this.formInline.email && !checkEmail(this.formInline.email)) {
        this.$message.error("邮箱输入格式有误");
        return;
      }
      if (this.formInline.applyCategoryId&&this.formInline.applyCategoryId.length) {
        param.applyCategoryIds = this.formInline.applyCategoryId
      }

      if (this.formInline.time && this.formInline.time.length) {
        param.pauseStartTime = this.formInline.time[0]
        param.pauseEndTime = this.formInline.time[1]
      }

      param.contactPhone = this.formInline.contactPhone;
      param.email = this.formInline.email;
      param.contactPerson = this.formInline.contactPerson;
      param.name = this.formInline.name;
      param.pauseType = this.formInline.pauseType;
    //  param.pageNum = this.models.pageNum
    //  param.pageSize = this.models.pageSize;
      param.isPaused =1
      const {code,data} = await getSupplierStorePage(param);
       if (code === 200) {
         let fields = {}
          SUPPLIER_PAUSE_LABEL.forEach(v => {
          if (v.type == 'on') {
            fields['index'] = v.label
          } else {
            if (v.prop) {
              fields[v.prop] = v.label
            }
          }
          })
          const entries = Object.entries(fields);
          if (entries.length > 0) {
            const firstEntry = entries.shift();
            entries.push(firstEntry);
          }
        const header = Object.fromEntries(entries);
          const manualWidthColumns = [
            { width: 10 },
            { width: 40 },
            { width: 40 },
            { width: 15 },
            { width: 15 },
            { width: 25 },
            { width: 15 },
            { width: 60 },
            { width: 15 },
            { width: 20 },
            { width: 50 }
          ];

        data.list.forEach((v, i) => {
          v.index = (i + 1)
          if (v.pauseTime) {
            let time = moment(v.pauseTime).format("YYYY-MM-DD");
            v.pauseTime = time
          }
          if (v.pauseEndDate) {
            let time = moment(v.pauseEndDate).format("YYYY-MM-DD");
            v.pauseEndDate = time
          }
          if (v.pauseType) {
            v.pauseType = v.pauseType == '1' ? '人工':'系统'
          }
        })
       
        if (this.$refs.createSupplier) {
          this.$refs.createSupplier.clearSelected()
          this.$refs.createSupplier.exportXlsx(header,data.list,manualWidthColumns,'暂停列表')
        }
      }
    }
  }
};
</script>
<style scoped>
.duo-file{
  display: flex;
  flex-wrap: wrap;
}
</style>